import type { App } from 'vue'
import { createVNode, render, nextTick } from 'vue'
import { debounce } from 'lodash-es'
import ExpandButton from '@/components/expandButton/index.vue'

const toggleHideFormItem = debounce(function (el: any, vnode: any) {
  const elWidth = el.getBoundingClientRect().width
  if (!elWidth) {
    return
  }
  const itemList = el
    .querySelector('.el-form.auto-grid')
    .querySelectorAll('.el-form-item:not(:last-child)')
  const lastItem = el.querySelector('.el-form.auto-grid').querySelector('.el-form-item:last-child')
  let sumWidth = 0
  const lastWidth = lastItem.clientWidth
  const visible = el.classList.contains('expand')
  itemList.forEach((item: any, index: any) => {
    const style = window.getComputedStyle(item)
    const marginLeft = parseFloat(style.marginLeft)
    const marginRight = parseFloat(style.marginRight)
    sumWidth += item.clientWidth + marginLeft + marginRight
    if (visible) {
      item.classList.remove('expand-hide')
    } else if (sumWidth + lastWidth > elWidth - 50) {
      item.classList.add('expand-hide')
    }
  })
  if (vnode?.component?.exposed) {
    if (sumWidth + lastWidth < elWidth - 50) {
      vnode.component.exposed.showExpand.value = false
    } else {
      vnode.component.exposed.showExpand.value = true
    }
  }
}, 200)
/**
 * el-form单行展开收起（query-expand）
 */
export function queryExpand(app: App) {
  // el-form单行展开收起（query-expand）
  app.directive('queryExpand', {
    mounted(el, binding) {
      if (!el.classList.contains('rev-query-form')) {
        el.classList.add('rev-query-form')
      }
      // 创建 ExpandContent 组件的虚拟节点
      const vnode = createVNode(ExpandButton, {
        onExpand: (val: any) => {
          if (val) {
            el.classList.add('expand')
          } else {
            el.classList.remove('expand')
          }
          if (vnode?.component?.exposed) {
            if (val) {
              vnode.component.exposed.queryExpand.value = true
            } else {
              vnode.component.exposed.queryExpand.value = false
            }
          }
          nextTick(() => {
            if (val) {
              const itemList =
                el
                  .querySelector('.el-form.auto-grid')
                  ?.querySelectorAll('.el-form-item:not(:last-child)') || []
              itemList.forEach((item: any) => {
                item.classList.remove('expand-hide')
              })
            } else {
              toggleHideFormItem(el, vnode)
            }
          })
        }
      })
      // 渲染 Vue 组件到 DOM 容器中
      render(vnode, el)
      // 监控页面大小变化
      const resizeObserver = new ResizeObserver(async () => {
        nextTick(() => {
          const itemList =
            el
              .querySelector('.el-form.auto-grid')
              ?.querySelectorAll('.el-form-item:not(:last-child)') || []
          itemList.forEach((item: any) => {
            item.classList.remove('expand-hide')
          })
          toggleHideFormItem(el, vnode)
        })
      })
      resizeObserver.observe(el)
    }
  })
}
